#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main() {
	int sock, listener;
	struct sockaddr_in addr;
	char buf[1024];
	int bytes_read;
	listener = socket(AF_INET, SOCK_STREAM, 0);
	
	if(listener < 0)
	{
		perror("socket");
		exit(errno);
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(3425);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
	{
		perror("bind");
		exit(errno);
	}

	listen(listener, 1);
	while(1)
	{
		struct sockaddr* client_addr;
		int client_address_len = sizeof(struct sockaddr_in);
		struct sockaddr_in client_address;
		sock = accept(listener, (struct sockaddr *) &client_address, &client_address_len);
		if(sock < 0)
		{
			perror("accept");
			exit(errno);
		}
		while(1)
		{
			bytes_read = recv(sock, buf, 1024, 0);
			if(bytes_read <= 0) break;
			char *address = inet_ntoa((struct in_addr) client_address.sin_addr);
			printf("echo to %s:%d\n", address, client_address.sin_port);
			send(sock, buf, bytes_read, 0);
		}
		close(sock);
	}
	return 0;
}

